<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AuthController
 *
 * @author Kamdem Kenmogne
 */
class AuthController {
    
    private  $app;
    
    public function __construct($app) 
    {
//        parent::__construct($app);
        $this->app = $app;
    }
    
    /**
     * Adding Middle Layer to authenticate every request
     * Checking if the request has valid api key in the 'Authorization' header
     */
    public function authenticate()
    {
       // Getting request headers
        $headers = apache_request_headers();
        $response = array();
        // Verifying Authorization Header
        if (isset($headers['Authorization'])) {
            // get the api key
            $api_key = $headers['Authorization'];
            // validating api key
            if (!$this->app->myDB->isValidApiKey($api_key)) {
                // api key is not present in users table
                $response["error"] = true;
                $response["message"] = "Access Denied. Invalid Api key";
                $this->echoResponse(401, $response);
                $this->app->stop();
            } else {
                
                // get user primary key id
                $this->app->user_id = $this->app->myDB->getUserId($api_key);
                $this->app->user_email = $this->app->myDB->getUserMail($api_key);
            }
        } else {
            // api key is missing in header
            $response["error"] = true;
            $response["message"] = "Api key is misssing";
            $this->echoResponse(400, $response);
            $this->app->stop();
        } 
    }
 
    /**
     * Verifying required params posted or not
     * @param type $required_fields
     */
    public function verifyRequiredParams($required_fields) 
    {
        $error = false;
        $error_fields = "";
        $request_params = array();
        $request_params = $_REQUEST;
        // Handling PUT request params
        if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
            //$app = \Slim\Slim::getInstance();
            parse_str($this->app->request()->getBody(), $request_params);
        }
        foreach ($required_fields as $field) {
            if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
                $error = true;
                $error_fields .= $field . ', ';
            }
        }

        if ($error) {
            // Required field(s) are missing or empty
            // echo error json and stop the app
            $response = array();
            $response["error"] = true;
            $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
            $this->echoResponse(400, $response);
            $this->app->stop();
        }
    }

    /**
     * Validating email address
     * @param type $email
     */
    public function validateEmail($email) {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $response["error"] = true;
            $response["message"] = 'Email address is not valid';
            $this->echoResponse(400, $response);
            $this->app->stop();
        }
    }
    
    /**
     * Echoing json response to client
     * @param String $status_code Http response code
     * @param Int $response Json response
     */
    public function echoResponse($status_code, $response) {
        // Http response code
        $this->app->status($status_code);
        $this->app->contentType('application/json');
        echo json_encode($response);
    }
}
